package com.sskj.givecoin.m.http;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.JsonReader;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.Request;
import com.sskj.givecoin.MyAppLication;
import com.sskj.givecoin.R;
import com.sskj.givecoin.common.App;
import com.sskj.givecoin.m.bean.HttpData;
import com.sskj.givecoin.m.bean.bean.HttpResponse;
import com.sskj.givecoin.p.base.BasePresenter;
import com.sskj.givecoin.utils.ToastUtil;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import okhttp3.ResponseBody;

/**
 * Created by lvzhihao on 17-7-4.
 */

public abstract class JsonCallBack<T> extends AbsCallback<T> {


    private BasePresenter mBasePresenter;

    private boolean showDialog = true;

    public JsonCallBack(BasePresenter basePresenter) {
        this.mBasePresenter = basePresenter;
        showDialog = true;
    }


    public JsonCallBack(BasePresenter basePresenter, boolean isShow) {
        this.mBasePresenter = basePresenter;
        showDialog = isShow;
    }

    public JsonCallBack() {
    }

    @Override
    public void onStart(Request<T, ? extends Request> request) {
        super.onStart(request);
        if (mBasePresenter != null) {
            if (showDialog) {
                mBasePresenter.showLoading();
            }
        }
    }


    @Override
    public void onSuccess(Response<T> response) {
        int status;
        String msg;
        if (response.body() instanceof HttpData){
            status = ((HttpData)response.body()).getStatus();
            msg = ((HttpData)response.body()).getMsg();
        }else if (response.body() instanceof HttpResponse){
            status = ((HttpResponse)response.body()).getCode();
            msg = ((HttpResponse)response.body()).getMsg();
        }else if (response.body() instanceof Map){
            Map<String, String> body = (Map<String, String>) response.body();
            status = Integer.valueOf(body.get("status"));
            msg = body.get("msg");
        }else {
            status = -1;
            msg = "";
        }
        if (status == 404){//账户被冻结
            ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(msg);
            if (mBasePresenter != null) {
                mBasePresenter.mContext.logout();
            }
        }else {
            if (response.body().toString().contains("200") || status == 200){
                _onSuccess(response);
            }else {
                if (status != 505){
                    if (!TextUtils.isEmpty(msg)&&!msg.equals("数据为空")){
                        ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(msg);
                    }
                }
            }
        }
        _onNewsSuccess(response);//这里适配行情资讯接口数据，没有 status
    }

    protected abstract void _onSuccess(Response<T> response);
    protected  void _onNewsSuccess(Response<T> response){

    }


    @Override
    public void onFinish() {
        super.onFinish();
        if (mBasePresenter != null) {
            mBasePresenter.hideLoading();
        }
    }


    @Override
    public T convertResponse(okhttp3.Response response) throws JsonParseException {
        ResponseBody body = response.body();
        if (body == null) return null;
        T data = null;
        try {
            Gson gson = new Gson();
            JsonReader jsonReader = new JsonReader(body.charStream());
            Type genericSuperclass = getClass().getGenericSuperclass();
            Type type = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
            data = gson.fromJson(jsonReader, type);
        } catch (JsonIOException e) {
            throw new JsonParseException();
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            throw new JsonParseException();
        }
        return data;
    }

    @Override
    public void onError(Response<T> response) {
        super.onError(response);
        if (mBasePresenter != null) {
            mBasePresenter.hideLoading();
        }
        if (response.getException() instanceof JsonParseException) {
//            ToastUtil.showShort(App.INSTANCE.getString(R.string.strJsonCallBack205));
        } else if (response.getException() instanceof UnknownHostException) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.strJsonCallBack206));
        } else if (response.getException() instanceof TimeoutException) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.strJsonCallBack207));
        } else  if (response.getException() instanceof SocketTimeoutException){
            ToastUtil.showShort(App.INSTANCE.getString(R.string.strJsonCallBack207));
        } else if (response.getException() instanceof ConnectException ) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.strJsonCallBack209));
        }
    }
}
